package m.system.exception;

import m.appserver.ActionRedirect;
import m.appserver.AuthInfoUtil;
import m.common.action.ActionMeta;
import m.system.util.AnnotationUtil;
import m.system.util.StringUtil;
import m.system.util.SystemUtil;
import manage.model.AdminLogin;

/**
 * 系统业务通用异常类
 */
public class MException extends Exception {

	private static final long serialVersionUID = 1L;
	private final Class<?> cl;
	private ActionRedirect redirect;

	/**
	 * 创建异常
	 *  clazz 记录异常的类
	 *  errorMessage 异常消息
	 */
	public MException(Class<?> clazz,String errorMessage){
		super(errorMessage);
		this.cl=clazz;
	}

	public ActionRedirect getRedirect() {
		return redirect;
	}

	/**
	 * 设置重定向，非自行捕获可按需重定向。（action方法向外抛出的异常）
	 */
	public MException setRedirect(ActionRedirect redirect) {
		this.redirect = redirect;
		return this;
	}

	/**
	 * 捕获异常后,记录
	 */
	public void record(){
		AdminLogin admin=null;
		String param="";
		try {
			admin=AuthInfoUtil.getSessionAdmin();
			if(null!=AuthInfoUtil.getRequestJson())
				param=AuthInfoUtil.getRequestJson().toJSONString();
		}catch (Exception ignored){}
		String name;
		if(null!=admin){
			name=admin.getRealname()+"("+admin.getUsername()+")";
		}else{
			name="无登录信息";
		}
		String msg="";
		StackTraceElement[] allEle=this.getStackTrace();
		for(StackTraceElement e : allEle){
			if(e.getClassName().equals("m.appserver.ServerHandler")) break;
			try{
				ActionMeta am=AnnotationUtil.getAnnotation4Class(ActionMeta.class,Class.forName(e.getClassName()));
				if(null!=am){
					msg="\r\n\tAction:"+e.getClassName()+"."+e.getMethodName()+" at"+e.getLineNumber()
					+";\r\n\turl:action/"+am.name()+"/"+e.getMethodName()
					+"\t param:"+param;
					break;
				}
			}catch (Exception ignored){}
		}
		if(StringUtil.isSpace(msg)){
			msg="\r\n\turl:"+AuthInfoUtil.getUri();
		}
		SystemUtil.printErr(name," => ",null!=cl?cl.getName():"error",":",this.getMessage(),
				"; ",msg);
	}
}
